<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addCateDialog">添加分类</el-button>
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <tree-table :data="cateList" :columns="columns" :selection-type="false" :expand-type="false" show-index index-text="#" border :show-row-hover="false">
        <template slot="isValid" scope="scope">
          <i v-if="!scope.row.cat_deleted" class="el-icon-success" style="color:lightgreen;"></i>
          <i v-else class="el-icon-error" style="color:red;"></i>
        </template>
        <template slot="order" scope="scope">
          <el-tag size="mini" v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag size="mini" type="success" v-else-if="scope.row.cat_level === 1">二级</el-tag>
          <el-tag size="mini" type="warning" v-else>三级</el-tag>
        </template>
        <template slot="handle" scope="scope">
          <el-button type="primary" size="mini" icon="el-icon-edit" @click="editCate(scope.row.cat_id)">编辑</el-button>
          <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteCate(scope.row.cat_id)">删除</el-button>
        </template>
      </tree-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="pagesizeChange"
        @current-change="pagenumChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[3, 5, 10, 15]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
    <!-- 添加分类 对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCateDialogVisible"
      width="50%" @close="addCateDialogClosed">
      <el-form label-width="100px" :model="addCateForm" :rules="addCateFormRules" ref="addCateFormRef">
        <el-form-item label="分类名称：" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类：">
          <el-cascader style="width:100%;"
            v-model="selectValue"
            :options="parentCateList"
            :props="cascaderProp"
            @change="parentCateChange" clearable change-on-select></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑分类 对话框 -->
    <el-dialog
      title="编辑分类"
      :visible.sync="editCateDialogVisible"
      width="50%" @close="editCateDialogClosed">
      <el-form label-width="100px" :model="editCateForm" :rules="editCateFormRules" ref="editCateFormRef">
        <el-form-item label="分类名称：" prop="cat_name">
          <el-input v-model="editCateForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCateDialog">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      // 商品分类列表数据
      cateList: [],
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      // 总数据条数
      total: 0,
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name'
        }, {
          label: '是否有效',
          prop: 'cat_deleted',
          type: 'template',
          template: 'isValid'
        }, {
          label: '排序',
          prop: 'cat_level',
          type: 'template',
          template: 'order'
        }, {
          label: '操作',
          type: 'template',
          template: 'handle'
        }
      ],
      // 添加分类对话框 默认隐藏
      addCateDialogVisible: false,
      // 添加分类对话框 表单绑定数据
      addCateForm: {
        cat_name: '',
        // 父级分类的id
        cat_pid: 0,
        // 分类的等级, 默认添加一级分类
        cat_level: 0
      },
      // 添加分类对话框校验规则
      addCateFormRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      },
      // 父级分类的列表
      parentCateList: [],
      cascaderProp: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      selectValue: [],
      // 编辑对话框隐藏
      editCateDialogVisible: false,
      editCateForm: {
        cat_name: ''
      },
      editCateFormRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 获取商品分类列表
    async getCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) return this.$message.error('获取商品分类列表失败')
      // console.log(res)
      this.cateList = res.data.result
      this.total = res.data.total
    },
    // 监听 每页显示条数
    pagesizeChange(val) {
      this.queryInfo.pagesize = val
      this.getCateList()
    },
    // 监听 页码值
    pagenumChange(val) {
      this.queryInfo.pagenum = val
      this.getCateList()
    },
    // 点击 添加分类 打开 添加分类 对话框
    addCateDialog() {
      this.getParentCateList()
      this.addCateDialogVisible = true
    },
    // 添加分类 对话框中 点击 确定 添加分类
    addCate() {
      this.$refs.addCateFormRef.validate(async valid => {
        if(!valid) return
        const { data: res } = await this.$http.post('categories', this.addCateForm)
        // console.log(res)
        if(res.meta.status !== 201) return this.$message.error('添加分类失败')
        this.addCateDialogVisible = false
        this.$message.success('添加分类成功')
        this.getCateList()
      })
    },
    addCateDialogClosed() {
      this.$refs.addCateFormRef.resetFields()
      this.selectValue = []
      this.addCateForm.cat_pid = 0
      this.addCateForm.cat_level = 0
    },
    // 获取父级分类列表
    async getParentCateList() {
      const { data: res } = await this.$http.get('categories', { params: { type: 2 } })
      if(res.meta.status !== 200) return this.$message.error('父级分类列表获取失败')
      // console.log(res.data)
      this.parentCateList = res.data
    },
    // 级联选择器 选择项发生变化 就触发此函数
    parentCateChange() {
      // 如果this.selectValue.length大于0 证明选中了父级分类
      if(this.selectValue.length > 0) {
        // 所填写的分类名称 的父级分类id 为this.selectValue最后一项
        this.addCateForm.cat_pid = this.selectValue[this.selectValue.length - 1]
        // 当前分类的等级正好与选择的值的长度相等
        this.addCateForm.cat_level = this.selectValue.length
      } else {
        this.addCateForm.cat_pid = 0
        this.addCateForm.cat_level = 0
      }
    },
    // 点击编辑按钮
    async editCate(id) {
      const { data: res } = await this.$http.get('categories/' + id)
      if(res.meta.status !== 200) return this.$message.error('获取该分类名称失败')
      this.editCateForm = res.data
      this.editCateDialogVisible = true
    },
    // 监听关闭编辑对话框重置表单
    editCateDialogClosed() {
      this.$refs.editCateFormRef.resetFields()
    },
    // 编辑对话框中 点击确定 修改分类名称
    editCateDialog() {
      this.$refs.editCateFormRef.validate(async valid => {
        if(!valid) return
        const { data: res } = await this.$http.put('categories/' + this.editCateForm.cat_id, { cat_name: this.editCateForm.cat_name })
        if(res.meta.status !== 200) return this.$message.error('修改分类名称失败')
        this.$message.success('修改分类名称成功')
        this.editCateDialogVisible = false
        this.getCateList()
      })
    },
    // 删除分类
    deleteCate(id) {
      this.$msgbox.confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete('categories/' + id)
        if(res.meta.status !== 200) return this.$message.error('删除分类失败')
        this.$message.success('删除分类成功!')
        this.getCateList()
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    }
  }
}
</script>
<style lang="less" scoped>
.el-table{
  margin-top: 15px;
  font-size: 12px;
}
.zk-table{
  font-size: 12px;
  margin-top: 20px;
}
</style>
